//
//  JPFile.m
//  Tanzi
//
//  Created by Jpwang on 16/11/22.
//  Copyright © 2016年 cdsb. All rights reserved.
//


#import "JPLogFile.h"

#ifndef JPLogFiledebug
#define JPLogFiledebug NO
#endif

@implementation JPLogFile

/*将数据写入本地*/
void writeLog(NSString *str) {
    if (!JPLogFiledebug) {
        return;
    }
    
    str = [NSString stringWithFormat:@"%@", str];
    NSLog(@"logFile -> %@", str);
    NSArray *pathList=NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *filename = [pathList objectAtIndex:0];
    filename=[filename stringByAppendingPathComponent:@"logfile.plist"];
    NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:filename];
    if (data == nil) {
        data = [[NSMutableDictionary alloc] init];
    }
    //添加内容
    NSString *key = [[NSString stringWithFormat:@"%f",CFAbsoluteTimeGetCurrent()] stringByReplacingOccurrencesOfString:@"" withString:@""];
    [data setObject:[str stringByReplacingOccurrencesOfString:@" " withString:@""] forKey:key];
    @try {
        BOOL isOK = [data writeToFile:filename atomically:YES];
        NSLog(@"写入日志文件结果 -> %d",isOK);
    } @catch (NSException *exception) {
        NSLog(@"写入日志文件exception -> %@",exception.description);
    } @finally {
        
    }
}

/*打印本地数据*/
void printLog(void) {
    if (!JPLogFiledebug) {
        return;
    }
    NSArray *pathList=NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);
    NSString *filename = [pathList objectAtIndex:0];
    filename=[filename stringByAppendingPathComponent:@"logfile.plist"];
    NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:filename];
    fprintf(stderr, "日志文件 -> :%s\n", [[NSString stringWithFormat:@"%@",data] UTF8String]);
}

/*从本地读取数据*/
NSMutableDictionary* readLog(void) {
    if (!JPLogFiledebug) {
        return nil;
    }
    NSArray *pathList=NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);
    NSString *filename = [pathList objectAtIndex:0];
    filename=[filename stringByAppendingPathComponent:@"logfile.plist"];
    NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:filename];
    return data;
}

/*清楚本地数据*/
void clearAll(void) {
    if (!JPLogFiledebug) {
        return;
    }
    NSArray *pathList=NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *filename = [pathList objectAtIndex:0];
    filename=[filename stringByAppendingPathComponent:@"logfile.plist"];
    NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:filename];
    if (data != nil) {
        [data removeAllObjects];
    }
    @try {
        BOOL isOK = [data writeToFile:filename atomically:YES];
        NSLog(@"清除日志文件结果 -> %d",isOK);
    } @catch (NSException *exception) {
        NSLog(@"清除日志文件exception -> %@",exception.description);
    } @finally {
        
    }
}
@end
